<?php
namespace admin\action;

use herosphp\bean\Beans;
use herosphp\core\Controller;
use herosphp\files\FileUtils;
use herosphp\http\HttpRequest;
use herosphp\session\Session;
use herosphp\utils\AjaxResult;
use herosphp\core\Loader;

/**
 * 行情分析action
 * @author yu
 */
class QuoteAnalysisAction extends CommonAction
{

    public $serviceBean = 'quote.analysis.service';

    public function index(HttpRequest $request)
    {
        $this->page = $request->getParameter('page', 'intval');
        $this->pagesize = $request->getParameter('pagesize', 'intval');
        if ($this->page <= 0) $this->page = 1;
        if ($this->pagesize <= 0) $this->pagesize = 15;

        $product_name = $request->getParameter('product_name');

        if ($product_name != '') {

            $conditions = array('product_name' => $product_name);
        }

        $quoteAnalysisService = Beans::get('quote.analysis.service');

        $quoteDataService = Beans::get('quote.data.service');

        $productNameByHotArr = $quoteDataService->getProductNameByHotArr();

        $result = $quoteAnalysisService->getList($this->pagesize, $this->page, $conditions);

        $this->generatePageMenu($result['total']);

        $this->assign('productNameByHotArr', $productNameByHotArr);

        $this->assign('items', $result['items']);
        $this->assign('product_name', $product_name);

        $this->assign('breadcrumb', array('行情管理', '行情分析列表'));

        $this->setView('quoteAnalysis/index');


    }

    public function details(HttpRequest $request)
    {

        $id = $request->getParameter('id');
        $quoteAnalysisService = Beans::get('quote.analysis.service');

        $managerModel = Loader::model('manager');

        $item = $quoteAnalysisService->getItem($id);

        $managerItem=$managerModel->getItem($item['manager_id']);

        $item['manager_name'] = $managerItem['username'];

        $this->assign('item', $item);

        $this->assign('breadcrumb', array('行情管理', '行情分析'));

        $this->setView("quoteAnalysis/detail");

    }


    public function add(HttpRequest $request)
    {

        $quoteDataService = Beans::get('quote.data.service');

        $productNameByHotArr = $quoteDataService->getProductNameByHotArr();

        $this->assign('productNameByHotArr', $productNameByHotArr);

        $this->assign('breadcrumb', array('行情管理', '行情分析列表'));

        $this->setView('quoteAnalysis/add');


    }

    public function edit(HttpRequest $request)
    {
        $id = $request->getParameter('id');

        $quoteDataService = Beans::get('quote.data.service');

        $productNameByHotArr = $quoteDataService->getProductNameByHotArr();

        $quoteAnalysisService = Beans::get('quote.analysis.service');

        $item = $quoteAnalysisService->getItem($id);

        $this->assign('item', $item);

        $this->assign('productNameByHotArr', $productNameByHotArr);

        $this->assign('breadcrumb', array('行情管理', '行情分析列表'));

        $this->setView('quoteAnalysis/edit');


    }

    public function insert(HttpRequest $request)
    {

        $data = $request->getParameter('data');
        $data['manager_id'] = $this->loginUser->getId();
        $data['adddate'] = myDate();

        $quoteAnalysisModel=Loader::model('quoteAnalysis');

        if($quoteAnalysisModel->getItem(array('product_name'=>$data['product_name'],'adddate'=>$data['adddate']))){

            AjaxResult::ajaxResult(AjaxResult::OP_FAILURE, '今天已发布此品名分析!');
        }else{
            parent::__insert($data);
        }




    }

    public function update(HttpRequest $request)
    {
        $data = $request->getParameter('data');
        $id = $request->getParameter('id');

        parent::__update($data, $id);
    }

    public function delete(HttpRequest $request)
    {

        parent::delete($request);
    }

    //编辑器上传方法 ， 仅允许上传图片
    public function kindeditor_upload(HttpRequest $request){

        //文件保存目录URL
        $save_url =  '/res/upload/quote/'.appId().'/' . trim($this->__image_save_path,'/').'/'.date('Y').'/'.date('m') . '/';

        //文件保存目录路径
        $save_path =  APP_ROOT . $save_url;
        //定义允许上传的文件扩展名
        //只允许上传图片
        $ext_arr = array(
            'image' => explode(',',$this->__allow_image_ext),
            //	'media' => explode(',',$this->__allow_media_ext),
            //	'file' => explode(',',$this->__allow_file_ext),
        );
        //最大文件大小
        $max_size = 2 * 1024 * 1024;

        FileUtils::makeFileDirs($save_path);

        $save_path = realpath($save_path) . '/';

        //PHP上传失败
        if (!empty($_FILES['imgFile']['error'])) {
            switch($_FILES['imgFile']['error']){
                case '1':
                    $error = '超过php.ini允许的大小。';
                    break;
                case '2':
                    $error = '超过表单允许的大小。';
                    break;
                case '3':
                    $error = '图片只有部分被上传。';
                    break;
                case '4':
                    $error = '请选择图片。';
                    break;
                case '6':
                    $error = '找不到临时目录。';
                    break;
                case '7':
                    $error = '写文件到硬盘出错。';
                    break;
                case '8':
                    $error = 'File upload stopped by extension。';
                    break;
                case '999':
                default:
                    $error = '未知错误。';
            }
            $this->alert($error);
        }

        //有上传文件时
        if (empty($_FILES) === false) {
            //原文件名
            $file_name = $_FILES['imgFile']['name'];
            //服务器上临时文件名
            $tmp_name = $_FILES['imgFile']['tmp_name'];
            //文件大小
            $file_size = $_FILES['imgFile']['size'];
            //检查文件名
            if (!$file_name) {
                $this->alert("请选择文件。");
            }
            //检查目录
            if (@is_dir($save_path) === false) {
                $this->alert("上传目录不存在。");
            }
            //检查目录写权限
            if (@is_writable($save_path) === false) {
                $this->alert("上传目录没有写权限。");
            }
            //检查是否已上传
            if (@is_uploaded_file($tmp_name) === false) {
                $this->alert("上传失败。");
            }
            //检查文件大小
            if ($file_size > $max_size) {
                $this->alert("上传文件大小超过限制。");
            }
            //检查目录名
            $dir_name = empty($_GET['dir']) ? 'image' : trim($_GET['dir']);
            if (empty($ext_arr[$dir_name])) {
                $this->alert("目录名不正确。");
            }
            //获得文件扩展名
            $temp_arr = explode(".", $file_name);
            $file_ext = array_pop($temp_arr);
            $file_ext = trim($file_ext);
            $file_ext = strtolower($file_ext);
            //检查扩展名
            /*if (in_array($file_ext, $ext_arr[$dir_name]) === false) {
                $this->alert("上传文件扩展名是不允许的扩展名。\n只允许" . implode(",", $ext_arr[$dir_name]) . "格式。");
            }*/
            //创建文件夹
            if ($dir_name !== '') {
                $save_path .= $dir_name . "/";
                $save_url .= $dir_name . "/";
                if (!file_exists($save_path)) {
                    mkdir($save_path);
                }
            }
            $ymd = date("Ymd");
            $save_path .= $ymd . "/";
            $save_url .= $ymd . "/";
            if (!file_exists($save_path)) {
                mkdir($save_path);
            }
            //新文件名
            $new_file_name = date("YmdHis") . '_' . rand(10000, 99999) . '.' . $file_ext;
            //移动文件
            $file_path = $save_path . $new_file_name;
            if (move_uploaded_file($tmp_name, $file_path) === false) {
                $this->alert("上传文件失败。");
            }
            @chmod($file_path, 0644);
            $file_url = $save_url . $new_file_name;

            header('Content-type: text/html; charset=UTF-8');
            echo json_encode(array('error' => 0, 'url' => $file_url));
            exit;
        }

    }

    private function alert($msg) {
        header('Content-type: text/html; charset=UTF-8');
        echo json_encode(array('error' => 1, 'message' => $msg));
        exit;
    }
}
